<template>
  <div>
    <Row type="flex" class="common_window_top" align="middle" justify="start">
      <Col span="4">
      <div>
          <span class="title">
            <Icon type="ios-home" size="45"/>机构管理</span>
      </div>
      </Col>
      <Col span="20">
      <div style="float: right">
        <Form ref="" label-position="right" :label-width="65" inline>
          <FormItem label="机构代码:" >
            <Input type="text" placeholder="机构代码" v-model="parameters.viewCode"/>
          </FormItem>
          <FormItem label="机构名称:">
            <Input type="text" placeholder="机构名称" v-model="parameters.officeName"/>
          </FormItem>
          <FormItem :label-width="0">
            <Button type="primary" @click="findButton">查询</Button>
          </FormItem>
          <FormItem :label-width="0" style="margin-left: 10px;">
            <Button type="success" @click="addOfficeButton">新增</Button>
          </FormItem>
        </Form>
      </div>
      </Col>
    </Row>
    <br>
    <Row class="common_window_down">
      <Col span="24">
      <Table border :columns="officeColumn" :data="officeList" @on-row-click="tableClick"></Table>
      </Col>
    </Row>
    <Modal v-model="addOrUpdateOffice.isShow" :title="addOrUpdateOffice.parameters.officeCode ? '修改机构' : '新增机构'">
      <Form ref="formValidate" :model="addOrUpdateOffice.parameters" :rules="addOrUpdateOffice.ruleValidate" label-position="right" :label-width="75" inline>
        <Row :gutter="3">
          <Col span="12">
            <FormItem label="父级机构:" prop="parentCode" style="width: 100%;">
              <Cascader :data="cascaderList" v-model="addOrUpdateOffice.cascaderDefult" :disabled="addOrUpdateOffice.parameters.officeCode ? true : false" change-on-select trigger="hover" @on-change="officeSelect" placeholder="为空说明是顶级机构"></Cascader>
            </FormItem>
          </Col>
          <Col span="12">
          <FormItem label="机构类型:" prop="officeType" style="width: 100%;">
            <Select v-model="addOrUpdateOffice.parameters.officeType">
              <Option v-for="(item,index) in dictArray.officeType" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="3">
          <Col span="12">
          <FormItem label="机构名称:" prop="officeName" style="width: 100%;">
            <Input v-model="addOrUpdateOffice.parameters.officeName" type="text" placeholder="请输入..."/>
          </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="机构代码:" prop="viewCode" style="width: 100%;">
              <Input v-model="addOrUpdateOffice.parameters.viewCode" type="text" placeholder="请输入..." />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="3">
          <Col span="12">
            <FormItem label="机构全称:" prop="fullName" style="width: 100%;">
              <Input v-model="addOrUpdateOffice.parameters.fullName" type="text" placeholder="请输入..." />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="负责人:" prop="leader" style="width: 100%;">
              <Input v-model="addOrUpdateOffice.parameters.leader" type="text" placeholder="请输入..." />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="3">
          <Col span="12">
            <FormItem label="办公电话:" prop="phone" style="width: 100%;">
              <Input v-model="addOrUpdateOffice.parameters.phone" type="text" placeholder="请输入..." />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="联系地址:" prop="address" style="width: 100%;">
              <Input v-model="addOrUpdateOffice.parameters.address" type="text" placeholder="请输入..." />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="3">
          <Col span="12">
          <FormItem label="邮政编码:" prop="zipCode" style="width: 100%;">
            <Input v-model="addOrUpdateOffice.parameters.zipCode" type="text" placeholder="请输入..." />
          </FormItem>
          </Col>
          <Col span="12">
          <FormItem label="电子邮箱:" prop="email" style="width: 100%;">
            <Input v-model="addOrUpdateOffice.parameters.email" type="text" placeholder="请输入..." />
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="3">
          <Col span="12">
          <FormItem label="本级排序:">
            <InputNumber :max="100000" :min="1" :precision="0" v-model="addOrUpdateOffice.parameters.treeSort"></InputNumber>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="3">
          <Col span="24">
          <FormItem label="描述:" style="width: 100%;">
            <Input v-model="addOrUpdateOffice.parameters.remarks" type="textarea" :rows="2" placeholder="请输入..."/>
          </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="primary" size="large" :loading="addOrUpdateOffice.loading" @click="sendOffice">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {findOfficeList,addOffice,updateOffice,updateOfficeStatus,findCascaderOffice} from "../../../api/sys/system/sysOffice";
  import {mapState} from "vuex";
  export default {
    name : 'sysSystemOffice',
    computed:{
      ...mapState([
        'dictObject',
        'dictArray'
      ])
    },
    data () {
      return {
        cascaderList : [],
        parameters : {
          viewCode : null,
          officeName : null
        },
        officeList : [],
        officeListItem : [],
        officeColumn : [
          {title : '机构名称',key : 'officeName',align : 'left',minWidth : 200,maxWidth : 300,tooltip : true,render : (h,parame)=>{
            var docu = [];
            if(parame.row.officeType == '0' && parame.row.treeLeaf != "1"){
                if(parame.row.unfold){
                  docu.push(h('Icon',{props:{type:'ios-arrow-down',size:'20'},style:{marginRight: '10px'}}));
                }else{
                  docu.push(h('Icon',{props:{type:'ios-arrow-back',size:'20'},style:{marginRight: '10px'}}));
                }
            }
            var marginLeft = 15 * (parame.row.treeLevel-1);
            if(parame.row.officeType == '1'){
              docu.push(h('Icon',{props:{type:'md-flower'},style:{marginLeft: '30px'}}));
            }else{
              if(parame.row.treeLeaf != "1"){
                docu.push(h('Icon',{props:{type:'md-home'}}));
              }else{
                docu.push(h('Icon',{props:{type:'md-home',},style:{marginLeft: '30px'}}));
              }

            }
            var name = h('span',{style:{marginLeft: '5px'}},parame.row.officeName);
            docu.push(name);
            return h('div',{style:{marginLeft: marginLeft+'px'}},docu);
            }},
          {title : '机构代码',key : 'viewCode',align : 'center',maxWidth : 130,tooltip : true},
          {title : '机构全称',key : 'fullName',align : 'center',tooltip : true},
          {title : '机构类型',key : 'officeType',align : 'center',maxWidth : 120,tooltip : true,render: (h,parame) =>{return h('span',this.dictObject.officeType[parame.row.officeType])}},
          {title : '负责人',key : 'leader',align : 'center',maxWidth : 130,tooltip : true},
          {title : '办公电话',key : 'phone',align : 'center',maxWidth : 120,tooltip : true},
          {title : '联系地址',key : 'address',align : 'center',tooltip : true},
          {title : '邮政编码',key : 'zipCode',align : 'center',maxWidth : 100,tooltip : true},
          {title : '电子邮箱',key : 'email',align : 'center',tooltip : true},
          {title : '状态',key : 'status',align : 'center',maxWidth : 70,tooltip : true,render: (h,parame) =>{return h('span',this.dictObject.status[parame.row.status])}},
          {title : '操作',align : 'center',minWidth : 180,maxWidth : 180,render : (h,parame) =>{
              var buttons = [];
              buttons.push(h('Button',{
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                nativeOn : {
                  click : ()=>{
                    this.addOrUpdateOffice.parameters.officeCode = parame.row.officeCode;
                    this.addOrUpdateOffice.parameters.parentCode = parame.row.parentCode == '0' ? '' : parame.row.parentCode;
                    this.addOrUpdateOffice.parameters.officeName = parame.row.officeName;
                    this.addOrUpdateOffice.parameters.viewCode = parame.row.viewCode;
                    this.addOrUpdateOffice.parameters.officeType = parame.row.officeType;
                    this.addOrUpdateOffice.parameters.fullName = parame.row.fullName;
                    this.addOrUpdateOffice.parameters.leader = parame.row.leader;
                    this.addOrUpdateOffice.parameters.phone = parame.row.phone;
                    this.addOrUpdateOffice.parameters.address = parame.row.address;
                    this.addOrUpdateOffice.parameters.zipCode = parame.row.zipCode;
                    this.addOrUpdateOffice.parameters.email = parame.row.email;
                    this.addOrUpdateOffice.parameters.treeSort = parame.row.treeSort;
                    this.addOrUpdateOffice.parameters.remarks = parame.row.remarks;
                    this.addOrUpdateOffice.cascaderDefult = parame.row.parentCode == '0' ? [] : parame.row.parentCodes.split(",");
                    this.addOrUpdateOffice.isShow = true;
                  }
                }
              },'修改'));
              if(parame.row.status == '0'){
                buttons.push(h('Button',{
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on : {
                    click : ()=>{
                      this.stopOffice(parame.row.officeCode);
                    }
                  }
                },'停用'));
              }else if(parame.row.status == '2'){
                buttons.push(h('Button',{
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on : {
                    click : ()=>{
                      this.startOffice(parame.row.officeCode);
                    }
                  }
                },'启用'));
              }
              buttons.push(h('Button',{
                props: {
                  type: 'error',
                  size: 'small'
                },
                on : {
                  click : ()=>{
                    this.deleteOffice(parame.row.officeCode);
                  }
                }
              },'删除'));
              return h('div',{},buttons)
            }}
        ],
        addOrUpdateOffice : {
          isShow : false,
          loading : false,
          cascaderDefult : [],
          parameters : {
            officeCode : null,
            parentCode : '',
            officeName : null,
            viewCode : null,
            officeType : null,
            fullName : null,
            leader : null,
            phone : null,
            address : null,
            zipCode : null,
            email : null,
            treeSort : 1,
            remarks : null,
          },
          ruleValidate : {
            // parentCode : { required: true, message: '必填！', trigger: 'change' },
            officeName : { required: true, message: '必填！', trigger: 'change' },
            viewCode : { required: true, message: '必填！', trigger: 'change' },
            officeType : { required: true, message: '必填！', trigger: 'change' },
            leader : { required: true, message: '必填！', trigger: 'change' },
          }
        }
      }
    },
    mounted(){
      this.findButton();
      //初始化机构选择器数据
      this.findCascaderData();
    },
    methods : {
      officeSelect (value,selectedData ){
        if(!value || value.length < 1){
          this.addOrUpdateOffice.parameters.parentCode = '';
        }else{
          this.addOrUpdateOffice.parameters.parentCode = selectedData[selectedData.length-1].value;
        }
      },
      findButton(){
        this.parameters.parentCode = "";
        this.findOfficeDatas();
      },
      findOfficeDatas(){
        findOfficeList(this.parameters).then(result =>{
          var data = result.data;
          if(data){
            this.officeList = data;
            this.officeListItem = [];
          }
        });
      },
      addOfficeButton (){
        this.addOrUpdateOffice.isShow = true;
        this.$refs['formValidate'].resetFields();
        this.addOrUpdateOffice.parameters.officeCode = null;
        this.addOrUpdateOffice.parameters.parentCode = '';
        this.addOrUpdateOffice.cascaderDefult = [];
      },
      sendOffice(){
        this.$refs['formValidate'].validate(valid=>{
          this.addOrUpdateOffice.loading = true;
          if(valid){

            if(this.addOrUpdateOffice.parameters.officeCode){
              //修改
              updateOffice(this.addOrUpdateOffice.parameters).then(result=>{
                var data = result.data;
                if(data){
                  this.addOrUpdateSuccess(false,this.addOrUpdateOffice.parameters.parentCode);
                }
              },error=>{
                this.addOrUpdateOffice.loading = false;
              })
            }else{
              //新增
              if(!this.addOrUpdateOffice.parameters.parentCode){
                this.addOrUpdateOffice.parameters.parentCode = '0';
              }
              addOffice(this.addOrUpdateOffice.parameters).then(result=>{
                var data = result.data;
                if(data){
                  this.addOrUpdateSuccess(true,this.addOrUpdateOffice.parameters.parentCode);
                }
              },error=>{
                this.addOrUpdateOffice.loading = false;
              });
            }
          }else{
            this.addOrUpdateOffice.loading = false;
          }
        });
      },
      addOrUpdateSuccess(or,parentCode){
        this.findCascaderData();
        this.addOrUpdateOffice.loading = false;
        this.addOrUpdateOffice.isShow = false;
        this.$Message.success(or ? '新增成功！' : '修改成功！' );
        this.findButton();
      },
      findCascaderData(){
        findCascaderOffice().then(result=>{
          var data = result.data;
          if(data){
            this.cascaderList = data;
            this.officeListItem = [];
          }
        });
      },
      tableClick(row,index){
        if(row.treeLeaf == "1" || row.officeType == '1'){
          return;
        }
        //控制展开箭头
        if(this.officeList[index].unfold){
          var item = [...this.officeList];
          item[index]['unfold'] = false;
          this.officeList = item;
        }else{
          var item1 = [...this.officeList];
          item1[index]['unfold'] = true;
          this.officeList = item1;
        }
        //循环判断是否有子元素,删除
        var sonOffice = [];
        for(var j = 0; j<this.officeList.length;j++){
          if(this.officeList[j].parentCodes && this.officeList[j].parentCodes.indexOf(row.officeCode) > 0){
            sonOffice.push(this.officeList[j]);
            this.officeList.splice(j--,1);
          }
        }
        //有代表已查询，则不查询,缓存子数据。
        if(sonOffice && sonOffice.length > 0){
          var obj = {};
          obj[row.officeCode] = sonOffice;
          //如果有重复的则先删除。
          for(var i = 0; i<this.officeListItem.length;i++){
              if(this.officeListItem[i][row.officeCode]){
                this.officeListItem.splice(i,1);
              }
          }
          this.officeListItem.push(obj);
        }else{
          //没有代表列表里面没有数据。
          var cache;
          var cacheIndex;
          for(var i = 0; i<this.officeListItem.length;i++){
            if(this.officeListItem[i][row.officeCode]){
              cache = this.officeListItem[i][row.officeCode];
              cacheIndex = i;
            }
          }
          //循环缓存里是否有数据，有则直接从缓存里拿
          if(cache){
            var item = [...this.officeList];
            cache.unshift(index+1, 0);
            Array.prototype.splice.apply(item,cache);
            this.officeList = item;
          }else{
            //缓存没有则重新查询
            this.parameters.parentCode = row.officeCode;
            findOfficeList(this.parameters).then(result =>{
              var data = result.data;
              if(data){
                var item = [...this.officeList];
                data.unshift(index+1, 0);
                Array.prototype.splice.apply(item,data);
                this.officeList = item;
              }
            });
          }
        }
      },
      stopOffice(officeCode){
        updateOfficeStatus({officeCode: officeCode,status : '2'}).then(result=>{
          this.$Message.success('停用成功！');
          this.findButton();
        });
      },
      startOffice(officeCode){
        updateOfficeStatus({officeCode: officeCode,status : '0'}).then(result=>{
          this.$Message.success('启用成功！');
          this.findButton();
        });
      },
      deleteOffice(officeCode){
        updateOfficeStatus({officeCode: officeCode,status : '1'}).then(result=>{
          this.$Message.success('删除成功！');
          this.findButton();
        });
      }
    }
  }
</script>

<style scoped>
</style>
